package exebuilder.controller;

import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.RuntimeUtil;
import exebuilder.command.CommandUtils;
import exebuilder.core.Controllers;
import exebuilder.data.AppConfig;
import exebuilder.ui.MessageBox;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;

public class SecondController implements Initializable {

    private static final Logger logger = LogManager.getLogger();
    public TextField jdkPathField;
    public TextField sourcePathField;
    public TextField mainJarFileField;
    public TextField mainClassField;
    public TextField libPathField;


    public void chooseJdkPath(ActionEvent actionEvent) {
        var directoryChooser = new DirectoryChooser();
        var path = directoryChooser.showDialog(null);
        if (path != null) {
            String jdkPath = path.getAbsolutePath();
            jdkPathField.setText(jdkPath);
            logger.debug("jdk path：{}", jdkPath);
            int jdkVersion = CommandUtils.getJdkVersion(jdkPath);
            AppConfig.getInstance().setJdkVersion(jdkVersion);
        }
    }

    public void chooseSourcePath(ActionEvent actionEvent) {
        var directoryChooser = new DirectoryChooser();
        var path = directoryChooser.showDialog(null);
        if (path != null) {
            String sourcePath = path.getAbsolutePath();
            sourcePathField.setText(sourcePath);
            logger.debug("source path：{}", sourcePath);
        }
    }

    public void chooseMainJarFile(ActionEvent actionEvent) {
        var fileChooser = new FileChooser();
        fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("可执行的jar文件", "*.jar"));
        if (StringUtils.isNotBlank(sourcePathField.getText())) {
            fileChooser.setInitialDirectory(new File(sourcePathField.getText()));
        }
        var file = fileChooser.showOpenDialog(null);
        if (file != null) {
            var fileName = file.getName();
            mainJarFileField.setText(fileName);
            logger.debug("mainJar file：{}", fileName);
            initMainClassFieldValue(file);
        }
    }

    private void initMainClassFieldValue(File file) {
        Manifest manifest = null;
        try (JarFile jarFile = new JarFile(file);) {
            manifest = jarFile.getManifest();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (manifest == null) {
            mainJarFileField.setText("");
            MessageBox.error("没有找到主类，请重新选择");
            throw new RuntimeException("没有找到主类，请重新选择");
        }
        Attributes attr = manifest.getMainAttributes();
        String classpath = attr.getValue("Main-Class");
        if (StringUtils.isBlank(classpath)) {
            mainJarFileField.setText("");
            MessageBox.error("没有找到主类，请重新选择");
            throw new RuntimeException("没有找到主类，请重新选择");
        }
        mainClassField.setText(classpath);
    }

    public void chooselibPath(ActionEvent actionEvent) {
        var directoryChooser = new DirectoryChooser();
        if (StringUtils.isNotBlank(sourcePathField.getText())) {
            directoryChooser.setInitialDirectory(new File(sourcePathField.getText()));
        }
        var path = directoryChooser.showDialog(null);
        if (path != null) {
            var libPath = path.getAbsolutePath();
            libPathField.setText(libPath);
            logger.debug("lib path：{}", libPath);
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        Controllers.add("second", this);
        jdkPathField.setText(AppConfig.getInstance().getJdkPath());
    }
}
